<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header class="header-container">
        <div class="headerTitle">查询条件</div>
        <div class="header-content">
          <el-form :model="headerSearchForm" label-width="auto" class="header-search-form">
            <el-form-item label="钢种族分档号">
              <el-select v-model="headerSearchForm.ypClass" placeholder="请选择" style="width:120px" size="small">
                <el-option label="全部" value="" />
                <el-option v-for="item in steelGradeRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="宽度分档号">
              <el-select v-model="headerSearchForm.widthClass" placeholder="请选择" style="width:120px" size="small">
                <el-option label="全部" value="" />
                <el-option v-for="item in widthRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="厚度分档号">
              <el-select v-model="headerSearchForm.thicknessClass" placeholder="请选择" style="width:120px" size="small">
                <el-option label="全部" value="" />
                <el-option v-for="item in thicknessRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="header-buttons">
            <el-button type="primary" @click="handleSearch" size="small">查询</el-button>
            <el-button type="primary" @click="handleReset" size="small">重置</el-button>
            <el-button type="primary" @click="handleExport" size="small">导出</el-button>
            <el-button type="primary" @click="handleAdd" size="small">添加</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="table-container-main">
          <el-table
            :data="tableData"
            :cell-class-name="bandCellClassName"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            v-loading="loading"
            ref="tableRef"
            :max-height="260"
            highlight-current-row
            @current-change="handleRowClick"
          >
            <el-table-column prop="serialNumber" label="序号" width="60" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 + (pagination.currentPage - 1) * pagination.pageSize }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="steelGrade" label="钢种" width="100" />
            <el-table-column prop="ypClass" label="钢种族分档号" width="110" />
            <el-table-column prop="widthClass" label="宽度分档号" width="100" />
            <el-table-column prop="thicknessClass" label="厚度分档号" width="100" />
            <el-table-column prop="gradeIndex" label="等级索引" width="100" />
            <el-table-column prop="allReds" label="总压下量" width="100" />
            <el-table-column prop="recCreateTime" label="优化时间" width="160" />
            <el-table-column label="优化前压下率" header-align="center">
              <el-table-column prop="s1Light" label="S1" width="80" />
              <el-table-column prop="s2Light" label="S2" width="80" />
              <el-table-column prop="s3Light" label="S3" width="80" />
              <el-table-column prop="s4Light" label="S4" width="80" />
              <el-table-column prop="s5Light" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化后压下率" header-align="center">
              <el-table-column prop="s1New" label="S1" width="80" />
              <el-table-column prop="s2New" label="S2" width="80" />
              <el-table-column prop="s3New" label="S3" width="80" />
              <el-table-column prop="s4New" label="S4" width="80" />
              <el-table-column prop="s5New" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化后压下率占比" header-align="center">
              <el-table-column prop="redsFinal1New" label="S1(%)" width="80" />
              <el-table-column prop="redsFinal2New" label="S2(%)" width="80" />
              <el-table-column prop="redsFinal3New" label="S3(%)" width="80" />
              <el-table-column prop="redsFinal4New" label="S4(%)" width="80" />
              <el-table-column prop="redsFinal5New" label="S5(%)" width="80" />
            </el-table-column>
            <el-table-column label="理论最大速度" header-align="center">
              <el-table-column prop="maxspeedOld" label="优化前" width="80" />
              <el-table-column prop="maxspeedNew" label="优化后" width="80" />
            </el-table-column>
            <el-table-column label="优化前轧制力" header-align="center">
              <el-table-column prop="rollingforceset1" label="S1" width="80" />
              <el-table-column prop="rollingforceset2" label="S2" width="80" />
              <el-table-column prop="rollingforceset3" label="S3" width="80" />
              <el-table-column prop="rollingforceset4" label="S4" width="80" />
              <el-table-column prop="rollingforceset5" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化后轧制力" header-align="center">
              <el-table-column prop="rollingforceset1New" label="S1" width="80" />
              <el-table-column prop="rollingforceset2New" label="S2" width="80" />
              <el-table-column prop="rollingforceset3New" label="S3" width="80" />
              <el-table-column prop="rollingforceset4New" label="S4" width="80" />
              <el-table-column prop="rollingforceset5New" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化前电机扭矩" header-align="center">
              <el-table-column prop="motormomentSet1" label="S1" width="80" />
              <el-table-column prop="motormomentSet2" label="S2" width="80" />
              <el-table-column prop="motormomentSet3" label="S3" width="80" />
              <el-table-column prop="motormomentSet4" label="S4" width="80" />
              <el-table-column prop="motormomentSet5" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化后电机扭矩" header-align="center">
              <el-table-column prop="motormomentSet1New" label="S1" width="80" />
              <el-table-column prop="motormomentSet2New" label="S2" width="80" />
              <el-table-column prop="motormomentSet3New" label="S3" width="80" />
              <el-table-column prop="motormomentSet4New" label="S4" width="80" />
              <el-table-column prop="motormomentSet5New" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化前功率" header-align="center">
              <el-table-column prop="motorpower1" label="S1" width="80" />
              <el-table-column prop="motorpower2" label="S2" width="80" />
              <el-table-column prop="motorpower3" label="S3" width="80" />
              <el-table-column prop="motorpower4" label="S4" width="80" />
              <el-table-column prop="motorpower5" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="优化后功率" header-align="center">
              <el-table-column prop="motorpower1New" label="S1" width="80" />
              <el-table-column prop="motorpower2New" label="S2" width="80" />
              <el-table-column prop="motorpower3New" label="S3" width="80" />
              <el-table-column prop="motorpower4New" label="S4" width="80" />
              <el-table-column prop="motorpower5New" label="S5" width="80" />
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleEdit(scope.row)" size="small">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(scope.row)" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 负荷分配曲线图：紧跟表格展示，无需滚动即可看到 -->
        <div class="chart-container">
          <div class="chart-title">负荷分配曲线</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div ref="chartBeforeRef" class="chart-item"></div>
            </el-col>
            <el-col :span="12">
              <div ref="chartAfterRef" class="chart-item"></div>
            </el-col>
          </el-row>
        </div>

        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>

  <!-- 新增/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :before-close="handleClose">
    <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogFormRef" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="钢种" prop="steelGrade">
            <el-input v-model="dialogForm.steelGrade" placeholder="请输入钢种" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="钢种族分档号" prop="ypClass">
            <el-select v-model="dialogForm.ypClass" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in steelGradeRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="宽度分档号" prop="widthClass">
            <el-select v-model="dialogForm.widthClass" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in widthRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="厚度分档号" prop="thicknessClass">
            <el-select v-model="dialogForm.thicknessClass" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in thicknessRangeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="优化时间" prop="recCreateTime">
            <el-date-picker
              v-model="dialogForm.recCreateTime"
              type="datetime"
              placeholder="请选择优化时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="dialogFormSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
  import { ref, reactive, onMounted, defineComponent, nextTick, onUnmounted } from 'vue';
  import { ElMessage, ElMessageBox, ElTable, type FormInstance, type FormRules } from 'element-plus';
  import { historyOptimizationRecordApi } from '/@/api/RollingSimulation/historyOptimizationRecord';
  import * as XLSX from 'xlsx';
  import * as echarts from 'echarts';

  interface SearchForm {
    ypClass: string;
    widthClass: string;
    thicknessClass: string;
  }

  interface DialogForm {
    id?: number;
    steelGrade: string;
    widthClass: number | string;
    thicknessClass: number | string;
    ypClass: number | string;
    gradeIndex: number | string;
    allReds: number | string;
    s1Light: number | string;
    s2Light: number | string;
    s3Light: number | string;
    s4Light: number | string;
    s5Light: number | string;
    s1New: number | string;
    s2New: number | string;
    s3New: number | string;
    s4New: number | string;
    s5New: number | string;
    rollingforceset1: number | string;
    rollingforceset2: number | string;
    rollingforceset3: number | string;
    rollingforceset4: number | string;
    rollingforceset5: number | string;
    rollingforceset1New: number | string;
    rollingforceset2New: number | string;
    rollingforceset3New: number | string;
    rollingforceset4New: number | string;
    rollingforceset5New: number | string;
    maxspeedNew: number | string;
    maxspeedOld: number | string;
    motormomentSet1: number | string;
    motormomentSet2: number | string;
    motormomentSet3: number | string;
    motormomentSet4: number | string;
    motormomentSet5: number | string;
    motormomentSet1New: number | string;
    motormomentSet2New: number | string;
    motormomentSet3New: number | string;
    motormomentSet4New: number | string;
    motormomentSet5New: number | string;
    motorpower1: number | string;
    motorpower2: number | string;
    motorpower3: number | string;
    motorpower4: number | string;
    motorpower5: number | string;
    motorpower1New: number | string;
    motorpower2New: number | string;
    motorpower3New: number | string;
    motorpower4New: number | string;
    motorpower5New: number | string;
    redsFinal1: number | string;
    redsFinal2: number | string;
    redsFinal3: number | string;
    redsFinal4: number | string;
    redsFinal5: number | string;
    redsFinal1New: number | string;
    redsFinal2New: number | string;
    redsFinal3New: number | string;
    redsFinal4New: number | string;
    redsFinal5New: number | string;
    recCreateTime: string | Date;
  }

  export default defineComponent({
    name: 'HistoryOptimizationRecord',
    setup() {
      const headerSearchForm = reactive<SearchForm>({
        ypClass: '',
        widthClass: '',
        thicknessClass: '',
      });

      const steelGradeRangeOptions = ref([
        { label: '1', value: '1' },
        { label: '2', value: '2' },
        { label: '3', value: '3' },
        { label: '4', value: '4' },
        { label: '5', value: '5' },
        { label: '6', value: '6' },
        { label: '7', value: '7' },
        { label: '8', value: '8' },
        { label: '9', value: '9' },
        { label: '10', value: '10' },
        { label: '11', value: '11' },
        { label: '12', value: '12' },
        { label: '13', value: '13' },
        { label: '14', value: '14' },
        { label: '15', value: '15' },
        { label: '16', value: '16' },
        { label: '17', value: '17' },
        { label: '18', value: '18' },
        { label: '19', value: '19' },
        { label: '20', value: '20' },
        { label: '21', value: '21' },
        { label: '22', value: '22' },
        { label: '23', value: '23' },
        { label: '24', value: '24' },
        { label: '25', value: '25' },
        { label: '26', value: '26' },
        { label: '27', value: '27' },
        { label: '28', value: '28' },
        { label: '29', value: '29' },
        { label: '30', value: '30' },
        { label: '31', value: '31' },
        { label: '32', value: '32' },
        { label: '33', value: '33' },
        { label: '34', value: '34' },
        { label: '35', value: '35' },
        { label: '36', value: '36' },
      ]);

      const widthRangeOptions = ref([
        { label: '0: [0,1000)', value: '0' },
        { label: '1: [1000,1250)', value: '1' },
        { label: '2: [1250,1450)', value: '2' },
        { label: '3: [1450,1650)', value: '3' },
        { label: '4: [1650,1850)', value: '4' },
        { label: '5: [1850,2050)', value: '5' },
        { label: '6: [2050,9999)', value: '6' }
      ]);

      const thicknessRangeOptions = ref([
        { label: '0: [0.25,0.325)', value: '0' },
        { label: '1: [0.325,0.375)', value: '1' },
        { label: '2: [0.375,0.425)', value: '2' },
        { label: '3: [0.425,0.475)', value: '3' },
        { label: '4: [0.475,0.575)', value: '4' },
        { label: '5: [0.575,0.675)', value: '5' },
        { label: '6: [0.675,0.825)', value: '6' },
        { label: '7: [0.825,0.925)', value: '7' },
        { label: '8: [0.925,1.05)', value: '8' },
        { label: '9: [1.05,1.25)', value: '9' },
        { label: '10: [1.25,1.55)', value: '10' },
        { label: '11: [1.55,1.85)', value: '11' },
        { label: '12: [1.85,2.1)', value: '12' },
        { label: '13: [2.1,2.60)', value: '13' },
        { label: '14: [2.60,9.9)', value: '14' }
      ]);

      const tableData = ref<any>([]);
      const tableRef = ref<InstanceType<typeof ElTable>>();
      const dialogFormRef = ref<FormInstance>();
      
      // 图表相关
      const chartBeforeRef = ref<HTMLElement | null>(null);
      const chartAfterRef = ref<HTMLElement | null>(null);
      let chartBeforeInstance: echarts.ECharts | null = null;
      let chartAfterInstance: echarts.ECharts | null = null;
      const chartLoading = ref(false);
      const currentSelectedRow = ref<any>(null); // 当前选中的行

      let dialogVisible = ref(false);
      let dialogTitle = ref('');
      const loading = ref(false);

      const pagination = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 0,
      });

      const dialogForm = reactive<DialogForm>({
        steelGrade: '',
        widthClass: '',
        thicknessClass: '',
        ypClass: '',
        gradeIndex: '',
        allReds: '',
        s1Light: '',
        s2Light: '',
        s3Light: '',
        s4Light: '',
        s5Light: '',
        s1New: '',
        s2New: '',
        s3New: '',
        s4New: '',
        s5New: '',
        rollingforceset1: '',
        rollingforceset2: '',
        rollingforceset3: '',
        rollingforceset4: '',
        rollingforceset5: '',
        rollingforceset1New: '',
        rollingforceset2New: '',
        rollingforceset3New: '',
        rollingforceset4New: '',
        rollingforceset5New: '',
        maxspeedNew: '',
        maxspeedOld: '',
        motormomentSet1: '',
        motormomentSet2: '',
        motormomentSet3: '',
        motormomentSet4: '',
        motormomentSet5: '',
        motormomentSet1New: '',
        motormomentSet2New: '',
        motormomentSet3New: '',
        motormomentSet4New: '',
        motormomentSet5New: '',
        motorpower1: '',
        motorpower2: '',
        motorpower3: '',
        motorpower4: '',
        motorpower5: '',
        motorpower1New: '',
        motorpower2New: '',
        motorpower3New: '',
        motorpower4New: '',
        motorpower5New: '',
        redsFinal1: '',
        redsFinal2: '',
        redsFinal3: '',
        redsFinal4: '',
        redsFinal5: '',
        redsFinal1New: '',
        redsFinal2New: '',
        redsFinal3New: '',
        redsFinal4New: '',
        redsFinal5New: '',
        recCreateTime: '',
      });

      const dialogFormRules = reactive<FormRules<DialogForm>>({
        steelGrade: [{ required: true, message: '请输入钢种', trigger: 'blur' }],
      });

      const handleClose = (done: () => void) => {
        ElMessageBox.confirm('确定要关闭窗口吗?', { confirmButtonText: '确定', cancelButtonText: '取消' })
          .then(() => {
            done();
          })
          .catch(() => {
            // catch error
          });
      };

      const cancel = () => {
        dialogVisible.value = false;
        dialogFormRef.value?.resetFields();
      };

      const dialogFormSubmit = async () => {
        if (!dialogFormRef.value) return;
        
        await dialogFormRef.value.validate((valid) => {
          if (valid) {
            submitForm();
          } else {
            ElMessage.warning('请完善表单信息');
          }
        });
      };

      // 时间格式转换函数：将正常时间转换为数据库格式 (YYYY-MM-DD-HH.mm.ss.SSSSSS)
      const formatTimeToDb = (time: string | Date): string => {
        if (!time) return '';
        const date = typeof time === 'string' ? new Date(time) : time;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const milliseconds = String(date.getMilliseconds()).padStart(3, '0') + '000';
        return `${year}-${month}-${day}-${hours}.${minutes}.${seconds}.${milliseconds}`;
      };

      // 时间格式转换函数：将数据库格式转换为正常显示格式 (YYYY-MM-DD HH:mm:ss)
      const formatTimeFromDb = (dbTime: string): string => {
        if (!dbTime) return '-';
        try {
          // 处理多种格式：
          // 1. 2025-11-18 00:00:00.0 (标准格式)
          // 2. 2025-11-16-23.34.36.849386 (特殊格式)
          
          // 先尝试标准格式（包含空格和冒号）
          if (dbTime.includes(' ') && dbTime.includes(':')) {
            // 格式：2025-11-18 00:00:00.0 或 2025-11-18 00:00:00
            const timeStr = dbTime.split('.')[0]; // 去掉毫秒部分
            return timeStr;
          }
          
          // 处理特殊格式：2025-11-16-23.34.36.849386
          const parts = dbTime.split('-');
          if (parts.length >= 4) {
            const datePart = `${parts[0]}-${parts[1]}-${parts[2]}`;
            const timePart = parts[3].replace(/\./g, ':').substring(0, 8);
            return `${datePart} ${timePart}`;
          }
          
          return dbTime;
        } catch (e) {
          return dbTime || '-';
        }
      };

      const submitForm = async () => {
        try {
          // 构建提交参数，确保类型正确
          const param: any = {
            steelGrade: dialogForm.steelGrade,
            widthClass: Number(dialogForm.widthClass),
            thicknessClass: Number(dialogForm.thicknessClass),
            ypClass: Number(dialogForm.ypClass),
            gradeIndex: Number(dialogForm.gradeIndex),
            allReds: Number(dialogForm.allReds),
            s1Light: dialogForm.s1Light ? Number(dialogForm.s1Light) : null,
            s2Light: dialogForm.s2Light ? Number(dialogForm.s2Light) : null,
            s3Light: dialogForm.s3Light ? Number(dialogForm.s3Light) : null,
            s4Light: dialogForm.s4Light ? Number(dialogForm.s4Light) : null,
            s5Light: dialogForm.s5Light ? Number(dialogForm.s5Light) : null,
            s1New: dialogForm.s1New ? Number(dialogForm.s1New) : null,
            s2New: dialogForm.s2New ? Number(dialogForm.s2New) : null,
            s3New: dialogForm.s3New ? Number(dialogForm.s3New) : null,
            s4New: dialogForm.s4New ? Number(dialogForm.s4New) : null,
            s5New: dialogForm.s5New ? Number(dialogForm.s5New) : null,
            rollingforceset1: dialogForm.rollingforceset1 ? Number(dialogForm.rollingforceset1) : null,
            rollingforceset2: dialogForm.rollingforceset2 ? Number(dialogForm.rollingforceset2) : null,
            rollingforceset3: dialogForm.rollingforceset3 ? Number(dialogForm.rollingforceset3) : null,
            rollingforceset4: dialogForm.rollingforceset4 ? Number(dialogForm.rollingforceset4) : null,
            rollingforceset5: dialogForm.rollingforceset5 ? Number(dialogForm.rollingforceset5) : null,
            rollingforceset1New: dialogForm.rollingforceset1New ? Number(dialogForm.rollingforceset1New) : null,
            rollingforceset2New: dialogForm.rollingforceset2New ? Number(dialogForm.rollingforceset2New) : null,
            rollingforceset3New: dialogForm.rollingforceset3New ? Number(dialogForm.rollingforceset3New) : null,
            rollingforceset4New: dialogForm.rollingforceset4New ? Number(dialogForm.rollingforceset4New) : null,
            rollingforceset5New: dialogForm.rollingforceset5New ? Number(dialogForm.rollingforceset5New) : null,
            maxspeedNew: dialogForm.maxspeedNew ? Number(dialogForm.maxspeedNew) : null,
            maxspeedOld: dialogForm.maxspeedOld ? Number(dialogForm.maxspeedOld) : null,
            motormomentSet1: dialogForm.motormomentSet1 ? Number(dialogForm.motormomentSet1) : null,
            motormomentSet2: dialogForm.motormomentSet2 ? Number(dialogForm.motormomentSet2) : null,
            motormomentSet3: dialogForm.motormomentSet3 ? Number(dialogForm.motormomentSet3) : null,
            motormomentSet4: dialogForm.motormomentSet4 ? Number(dialogForm.motormomentSet4) : null,
            motormomentSet5: dialogForm.motormomentSet5 ? Number(dialogForm.motormomentSet5) : null,
            motormomentSet1New: dialogForm.motormomentSet1New ? Number(dialogForm.motormomentSet1New) : null,
            motormomentSet2New: dialogForm.motormomentSet2New ? Number(dialogForm.motormomentSet2New) : null,
            motormomentSet3New: dialogForm.motormomentSet3New ? Number(dialogForm.motormomentSet3New) : null,
            motormomentSet4New: dialogForm.motormomentSet4New ? Number(dialogForm.motormomentSet4New) : null,
            motormomentSet5New: dialogForm.motormomentSet5New ? Number(dialogForm.motormomentSet5New) : null,
            motorpower1: dialogForm.motorpower1 ? Number(dialogForm.motorpower1) : null,
            motorpower2: dialogForm.motorpower2 ? Number(dialogForm.motorpower2) : null,
            motorpower3: dialogForm.motorpower3 ? Number(dialogForm.motorpower3) : null,
            motorpower4: dialogForm.motorpower4 ? Number(dialogForm.motorpower4) : null,
            motorpower5: dialogForm.motorpower5 ? Number(dialogForm.motorpower5) : null,
            motorpower1New: dialogForm.motorpower1New ? Number(dialogForm.motorpower1New) : null,
            motorpower2New: dialogForm.motorpower2New ? Number(dialogForm.motorpower2New) : null,
            motorpower3New: dialogForm.motorpower3New ? Number(dialogForm.motorpower3New) : null,
            motorpower4New: dialogForm.motorpower4New ? Number(dialogForm.motorpower4New) : null,
            motorpower5New: dialogForm.motorpower5New ? Number(dialogForm.motorpower5New) : null,
            redsFinal1: dialogForm.redsFinal1 ? Number(dialogForm.redsFinal1) : null,
            redsFinal2: dialogForm.redsFinal2 ? Number(dialogForm.redsFinal2) : null,
            redsFinal3: dialogForm.redsFinal3 ? Number(dialogForm.redsFinal3) : null,
            redsFinal4: dialogForm.redsFinal4 ? Number(dialogForm.redsFinal4) : null,
            redsFinal5: dialogForm.redsFinal5 ? Number(dialogForm.redsFinal5) : null,
            redsFinal1New: dialogForm.redsFinal1New ? Number(dialogForm.redsFinal1New) : null,
            redsFinal2New: dialogForm.redsFinal2New ? Number(dialogForm.redsFinal2New) : null,
            redsFinal3New: dialogForm.redsFinal3New ? Number(dialogForm.redsFinal3New) : null,
            redsFinal4New: dialogForm.redsFinal4New ? Number(dialogForm.redsFinal4New) : null,
            redsFinal5New: dialogForm.redsFinal5New ? Number(dialogForm.redsFinal5New) : null,
            recCreateTime: dialogForm.recCreateTime ? formatTimeToDb(dialogForm.recCreateTime) : null,
          };
          
          // 移除空值字段
          Object.keys(param).forEach(key => {
            if (param[key] === null || param[key] === '' || param[key] === undefined) {
              delete param[key];
            }
          });
          
          // 判断是新增还是修改
          if (dialogForm.id) {
            // 编辑模式：使用新的参数格式 { id: xxx, data: { ... } }
            const updatePayload = {
              id: dialogForm.id,
              data: param
            };
            await historyOptimizationRecordApi.update(updatePayload);
            ElMessage.success('修改成功');
          } else {
            // 新增模式：调用add接口
            await historyOptimizationRecordApi.add(param);
            ElMessage.success('添加成功');
          }
          
          cancel();
          fetchTableData();
        } catch (error: any) {
          console.error('操作失败:', error);
          ElMessage.error('操作失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
        }
      };

      const fetchTableData = async () => {
        loading.value = true;
        try {
          // 构建查询条件对象
          const condition: any = {};
          if (headerSearchForm.ypClass) {
            condition.ypClass = headerSearchForm.ypClass;
          }
          if (headerSearchForm.widthClass) {
            condition.widthClass = headerSearchForm.widthClass;
          }
          if (headerSearchForm.thicknessClass) {
            condition.thicknessClass = headerSearchForm.thicknessClass;
          }
          
          const param: any = {
            pageIndex: pagination.currentPage,
            pageSize: pagination.pageSize,
            condition: condition,
          };
          
          console.log('查询参数:', param);
          const res = await historyOptimizationRecordApi.page(param);
          console.log('接口返回:', res);
          
          // 处理返回数据，添加格式化
          const records = res.data.data.records || res.data.data || [];
          tableData.value = records.map((record: any) => ({
            ...record,
            recCreateTime: formatTimeFromDb(record.recCreateTime),
            s1Light: record.s1Light !== undefined ? Number(record.s1Light).toFixed(2) : '-',
            s2Light: record.s2Light !== undefined ? Number(record.s2Light).toFixed(2) : '-',
            s3Light: record.s3Light !== undefined ? Number(record.s3Light).toFixed(2) : '-',
            s4Light: record.s4Light !== undefined ? Number(record.s4Light).toFixed(2) : '-',
            s5Light: record.s5Light !== undefined ? Number(record.s5Light).toFixed(2) : '-',
            s1New: record.s1New !== undefined ? Number(record.s1New).toFixed(2) : '-',
            s2New: record.s2New !== undefined ? Number(record.s2New).toFixed(2) : '-',
            s3New: record.s3New !== undefined ? Number(record.s3New).toFixed(2) : '-',
            s4New: record.s4New !== undefined ? Number(record.s4New).toFixed(2) : '-',
            s5New: record.s5New !== undefined ? Number(record.s5New).toFixed(2) : '-',
            redsFinal1New: record.redsFinal1New !== undefined ? Number(record.redsFinal1New).toFixed(2) : '-',
            redsFinal2New: record.redsFinal2New !== undefined ? Number(record.redsFinal2New).toFixed(2) : '-',
            redsFinal3New: record.redsFinal3New !== undefined ? Number(record.redsFinal3New).toFixed(2) : '-',
            redsFinal4New: record.redsFinal4New !== undefined ? Number(record.redsFinal4New).toFixed(2) : '-',
            redsFinal5New: record.redsFinal5New !== undefined ? Number(record.redsFinal5New).toFixed(2) : '-',
            maxspeedOld: record.maxspeedOld !== undefined ? Number(record.maxspeedOld).toFixed(2) : '-',
            maxspeedNew: record.maxspeedNew !== undefined ? Number(record.maxspeedNew).toFixed(2) : '-',
            rollingforceset1: record.rollingforceset1 !== undefined ? Number(record.rollingforceset1).toFixed(2) : '-',
            rollingforceset2: record.rollingforceset2 !== undefined ? Number(record.rollingforceset2).toFixed(2) : '-',
            rollingforceset3: record.rollingforceset3 !== undefined ? Number(record.rollingforceset3).toFixed(2) : '-',
            rollingforceset4: record.rollingforceset4 !== undefined ? Number(record.rollingforceset4).toFixed(2) : '-',
            rollingforceset5: record.rollingforceset5 !== undefined ? Number(record.rollingforceset5).toFixed(2) : '-',
            rollingforceset1New: record.rollingforceset1New !== undefined ? Number(record.rollingforceset1New).toFixed(2) : '-',
            rollingforceset2New: record.rollingforceset2New !== undefined ? Number(record.rollingforceset2New).toFixed(2) : '-',
            rollingforceset3New: record.rollingforceset3New !== undefined ? Number(record.rollingforceset3New).toFixed(2) : '-',
            rollingforceset4New: record.rollingforceset4New !== undefined ? Number(record.rollingforceset4New).toFixed(2) : '-',
            rollingforceset5New: record.rollingforceset5New !== undefined ? Number(record.rollingforceset5New).toFixed(2) : '-',
            motormomentSet1: record.motormomentSet1 !== undefined ? Number(record.motormomentSet1).toFixed(2) : '-',
            motormomentSet2: record.motormomentSet2 !== undefined ? Number(record.motormomentSet2).toFixed(2) : '-',
            motormomentSet3: record.motormomentSet3 !== undefined ? Number(record.motormomentSet3).toFixed(2) : '-',
            motormomentSet4: record.motormomentSet4 !== undefined ? Number(record.motormomentSet4).toFixed(2) : '-',
            motormomentSet5: record.motormomentSet5 !== undefined ? Number(record.motormomentSet5).toFixed(2) : '-',
            motormomentSet1New: record.motormomentSet1New !== undefined ? Number(record.motormomentSet1New).toFixed(2) : '-',
            motormomentSet2New: record.motormomentSet2New !== undefined ? Number(record.motormomentSet2New).toFixed(2) : '-',
            motormomentSet3New: record.motormomentSet3New !== undefined ? Number(record.motormomentSet3New).toFixed(2) : '-',
            motormomentSet4New: record.motormomentSet4New !== undefined ? Number(record.motormomentSet4New).toFixed(2) : '-',
            motormomentSet5New: record.motormomentSet5New !== undefined ? Number(record.motormomentSet5New).toFixed(2) : '-',
            motorpower1: record.motorpower1 !== undefined ? Number(record.motorpower1).toFixed(2) : '-',
            motorpower2: record.motorpower2 !== undefined ? Number(record.motorpower2).toFixed(2) : '-',
            motorpower3: record.motorpower3 !== undefined ? Number(record.motorpower3).toFixed(2) : '-',
            motorpower4: record.motorpower4 !== undefined ? Number(record.motorpower4).toFixed(2) : '-',
            motorpower5: record.motorpower5 !== undefined ? Number(record.motorpower5).toFixed(2) : '-',
            motorpower1New: record.motorpower1New !== undefined ? Number(record.motorpower1New).toFixed(2) : '-',
            motorpower2New: record.motorpower2New !== undefined ? Number(record.motorpower2New).toFixed(2) : '-',
            motorpower3New: record.motorpower3New !== undefined ? Number(record.motorpower3New).toFixed(2) : '-',
            motorpower4New: record.motorpower4New !== undefined ? Number(record.motorpower4New).toFixed(2) : '-',
            motorpower5New: record.motorpower5New !== undefined ? Number(record.motorpower5New).toFixed(2) : '-',
          }));
          pagination.total = res.data.count || res.data.total || 0;
          
          // 如果有数据，使用第一条数据的分档号和优化时间加载图表
          if (records.length > 0) {
            const firstRecord = records[0];
            currentSelectedRow.value = firstRecord;
            // 设置第一行为选中状态
            nextTick(() => {
              tableRef.value?.setCurrentRow(firstRecord);
            });
            // 提取优化时间的日期部分（YYYY-MM-DD）
            const optimizeDate = extractDateFromTime(firstRecord.recCreateTime);
            loadChartData(firstRecord.ypClass, firstRecord.widthClass, firstRecord.thicknessClass, optimizeDate);
          }
          
          ElMessage.success('查询成功');
        } catch (error: any) {
          console.error('查询失败:', error);
          ElMessage.error('获取数据失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
          tableData.value = [];
          pagination.total = 0;
        } finally {
          loading.value = false;
        }
      };

      const handleSearch = () => {
        pagination.currentPage = 1;
        fetchTableData();
      };

      const handleReset = () => {
        headerSearchForm.ypClass = '';
        headerSearchForm.widthClass = '';
        headerSearchForm.thicknessClass = '';
        handleSearch();
      };

      const handleExport = () => {
        if (!tableData.value.length) {
          ElMessage.error('导出Excel失败: 当前暂无数据');
          return;
        }

        try {
          const columns = tableRef.value?.columns;
          if (!columns || !(Array.isArray(columns) && columns.length)) {
            ElMessage.error('导出Excel失败: 表格列配置错误');
            return;
          }

          const headerMap: Record<string, string> = {};
          columns.forEach((column: any) => {
            if (column.property && column.property !== 'serialNumber') {
              headerMap[column.property] = column.label;
            }
          });

          const columnProperties = Object.keys(headerMap);
          const ws = XLSX.utils.json_to_sheet(tableData.value, { header: columnProperties });
          const headerRow = Object.values(headerMap);
          XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: 'A1' });

          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

          const formattedDateTime = new Date()
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false,
            })
            .replace(/\//g, '-')
            .replace(/\s/g, '_')
            .replace(/:/g, '-');

          XLSX.writeFile(wb, '历史推优记录_' + formattedDateTime + '.xlsx');
          ElMessage.success('导出成功');
        } catch (error: any) {
          ElMessage.error('导出Excel失败: ' + error.message);
        }
      };

      const handleAdd = () => {
        dialogVisible.value = true;
        dialogTitle.value = '新增';
        Object.assign(dialogForm, {
          steelGrade: '',
          widthClass: '',
          thicknessClass: '',
          ypClass: '',
          recCreateTime: '',
        });
      };

      const handleEdit = (row: any) => {
        dialogVisible.value = true;
        dialogTitle.value = '编辑';
        // 编辑时需要将数据库格式的时间转换为Date对象供日期选择器使用
        const editData: any = {
          steelGrade: row.steelGrade || '',
          widthClass: row.widthClass || '',
          thicknessClass: row.thicknessClass || '',
          ypClass: row.ypClass || '',
          recCreateTime: '',
          id: row.id,
        };
        
        if (row.recCreateTime && typeof row.recCreateTime === 'string') {
          try {
            // 将数据库格式转换为标准时间格式再转为Date
            const normalTime = formatTimeFromDb(row.recCreateTime);
            editData.recCreateTime = new Date(normalTime);
          } catch (e) {
            editData.recCreateTime = '';
          }
        }
        
        Object.assign(dialogForm, editData);
      };

      const handleDelete = async (row: any) => {
        ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            try {
              await historyOptimizationRecordApi.deleteOneById(row.id);
              ElMessage.success('删除成功');
              fetchTableData();
            } catch (error: any) {
              console.error('删除失败:', error);
              ElMessage.error('删除失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
            }
          })
          .catch(() => {});
      };

      const handleSizeChange = (val: number) => {
        pagination.pageSize = val;
        fetchTableData();
      };

      const handleCurrentChange = (val: number) => {
        pagination.currentPage = val;
        fetchTableData();
      };

      // 从时间字符串中提取日期部分（YYYY-MM-DD）
      const extractDateFromTime = (timeStr: string): string => {
        if (!timeStr || timeStr === '-') return '';
        // 提取 YYYY-MM-DD 部分
        const datePart = timeStr.split(' ')[0];
        return datePart || '';
      };

      // 处理行点击事件
      const handleRowClick = (row: any) => {
        if (!row) return;
        currentSelectedRow.value = row;
        // 提取优化时间的日期部分
        const optimizeDate = extractDateFromTime(row.recCreateTime);
        loadChartData(row.ypClass, row.widthClass, row.thicknessClass, optimizeDate);
      };

      // 加载图表数据
      const loadChartData = async (ypClass: any, widthClass: any, thicknessClass: any, optimizeDate: string = '') => {
        if (!ypClass && ypClass !== 0 && !widthClass && widthClass !== 0 && !thicknessClass && thicknessClass !== 0) {
          return;
        }
        
        chartLoading.value = true;
        try {
          const baseParam = {
            ypClass: Number(ypClass),
            widthClass: Number(widthClass),
            thicknessClass: Number(thicknessClass),
          };

          // 优化后传 startDate，优化前传 endDate
          const param1 = { ...baseParam, startDate: optimizeDate, endDate: '' };
          const param2 = { ...baseParam, startDate: '', endDate: optimizeDate };

          console.log('图表查询参数1 (优化后-startDate):', param1);
          console.log('图表查询参数2 (优化前-endDate):', param2);

          const [res1, res2] = await Promise.all([
            historyOptimizationRecordApi.findLoadDistributionCurveData(param1),
            historyOptimizationRecordApi.findLoadDistributionCurveData(param2)
          ]);

          console.log('图表接口返回1 (优化后):', res1);
          console.log('图表接口返回2 (优化前):', res2);

          const mergedData = mergeChartData(res1.data, res2.data);

          // 根据返回数据渲染图表
          await nextTick();
          renderCharts(mergedData);
        } catch (error: any) {
          console.error('加载图表数据失败:', error);
          ElMessage.error('加载图表数据失败: ' + (error?.response?.data?.msg || error?.message || '未知错误'));
        } finally {
          chartLoading.value = false;
        }
      };

      // 合并两次接口返回的图表数据
      const mergeChartData = (data1: any, data2: any): any => {
        // 期望：data1、data2 均为 { data: Array<Record> }，Record 含 power1~power5 等字段
        // 注意：按需求约定
        // - 传 startDate 的结果代表“优化后”（after）
        // - 传 endDate   的结果代表“优化前”（before）
        const afterArr = Array.isArray(data1?.data)
          ? data1.data
          : Array.isArray(data1)
          ? data1
          : Array.isArray(data1?.afterData)
          ? data1.afterData
          : Array.isArray(data1?.data?.afterData)
          ? data1.data.afterData
          : [];

        const beforeArr = Array.isArray(data2?.data)
          ? data2.data
          : Array.isArray(data2)
          ? data2
          : Array.isArray(data2?.beforeData)
          ? data2.beforeData
          : Array.isArray(data2?.data?.beforeData)
          ? data2.data.beforeData
          : [];

        return { beforeData: beforeArr, afterData: afterArr };
      };
      
      // 渲染图表
      const renderCharts = (data: any) => {
        // 初始化图表
        if (!chartBeforeInstance && chartBeforeRef.value) {
          chartBeforeInstance = echarts.init(chartBeforeRef.value);
        }
        if (!chartAfterInstance && chartAfterRef.value) {
          chartAfterInstance = echarts.init(chartAfterRef.value);
        }
        
        // 横坐标：S1-S4
        const xAxisData = ['S1', 'S2', 'S3', 'S4'];
        
        // 处理优化前数据
        const beforeSeries: any[] = [];
        const beforeLegend: string[] = [];
        
        // 处理优化后数据
        const afterSeries: any[] = [];
        const afterLegend: string[] = [];
        
        // 根据实际返回数据结构处理数据
        // 可能的返回数据结构：
        // 1. { beforeData: [...], afterData: [...] } - 数组格式
        // 2. { beforeData: {...}, afterData: {...} } - 对象格式
        // 3. { data: { before: [...], after: [...] } } - 嵌套格式
        // 4. 直接返回数组格式
        console.log('图表数据:', data);
        
        let beforeDataArray: any[] = [];
        let afterDataArray: any[] = [];
        
        // 尝试多种数据格式解析
        if (Array.isArray(data)) {
          // 直接是数组格式
          beforeDataArray = data;
        } else if (data && data.data) {
          // 嵌套在 data 中
          if (Array.isArray(data.data.before) || Array.isArray(data.data.beforeData)) {
            beforeDataArray = data.data.before || data.data.beforeData || [];
          }
          if (Array.isArray(data.data.after) || Array.isArray(data.data.afterData)) {
            afterDataArray = data.data.after || data.data.afterData || [];
          }
        } else if (data) {
          // 对象格式
          if (Array.isArray(data.before) || Array.isArray(data.beforeData)) {
            beforeDataArray = data.before || data.beforeData || [];
          }
          if (Array.isArray(data.after) || Array.isArray(data.afterData)) {
            afterDataArray = data.after || data.afterData || [];
          } else if (typeof data.beforeData === 'object' && !Array.isArray(data.beforeData)) {
            // 对象格式，需要转换为数组
            beforeDataArray = Object.values(data.beforeData);
          }
          if (typeof data.afterData === 'object' && !Array.isArray(data.afterData)) {
            afterDataArray = Object.values(data.afterData);
          }
        }
        
        // 处理优化前数据（只保留前30条）
        if (Array.isArray(beforeDataArray) && beforeDataArray.length > 0) {
          const limitedBeforeData = beforeDataArray.slice(0, 30);
          limitedBeforeData.forEach((item: any, index: number) => {
            const seriesName = `系列${index + 1}`;
            beforeLegend.push(seriesName);
            // 优化前：使用 power1~power4
            const seriesData: number[] = [
              Number(item.power1) || 0,
              Number(item.power2) || 0,
              Number(item.power3) || 0,
              Number(item.power4) || 0,
            ];
            beforeSeries.push({
              name: seriesName,
              type: 'line',
              data: seriesData.length === 4 ? seriesData : [0, 0, 0, 0],
              smooth: false,
              itemStyle: {
                color: getColorByIndex(index)
              }
            });
          });
        }
        
        // 处理优化后数据（只保留前30条）
        if (Array.isArray(afterDataArray) && afterDataArray.length > 0) {
          const limitedAfterData = afterDataArray.slice(0, 30);
          limitedAfterData.forEach((item: any, index: number) => {
            const seriesName = `系列${index + 1}`;
            afterLegend.push(seriesName);
            // 优化后：也使用 power1~power4（若后端提供其它字段可在此切换）
            const seriesData: number[] = [
              Number(item.power1) || 0,
              Number(item.power2) || 0,
              Number(item.power3) || 0,
              Number(item.power4) || 0,
            ];
            afterSeries.push({
              name: seriesName,
              type: 'line',
              data: seriesData.length === 4 ? seriesData : [0, 0, 0, 0],
              smooth: false,
              itemStyle: {
                color: getColorByIndex(index)
              }
            });
          });
        }

        // 动态计算 Y 轴范围
        const allBefore = beforeSeries.flatMap((s: any) => s.data || []);
        const allAfter = afterSeries.flatMap((s: any) => s.data || []);
        const allVals = [...allBefore, ...allAfter].filter((v) => typeof v === 'number' && !isNaN(v));
        const yMin = 0;
        const yMax = allVals.length ? Math.ceil(Math.max(...allVals) / 100) * 100 : 6000;
        
        // 优化前图表配置
        if (chartBeforeInstance) {
          const beforeOption = {
            title: {
              text: '负荷分配优化前',
              left: 'center',
              textStyle: {
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              }
            },
            legend: {
              data: beforeLegend,
              top: 30,
              type: 'scroll',
              orient: 'horizontal'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              top: '20%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxisData
            },
            yAxis: {
              type: 'value',
              name: '功率',
              min: yMin,
              max: yMax,
              splitLine: {
                show: true
              }
            },
            series: beforeSeries
          };
          chartBeforeInstance.setOption(beforeOption, true);
        }
        
        // 优化后图表配置
        if (chartAfterInstance) {
          const afterOption = {
            title: {
              text: '负荷分配优化后',
              left: 'center',
              textStyle: {
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              }
            },
            legend: {
              data: afterLegend,
              top: 30,
              type: 'scroll',
              orient: 'horizontal'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              top: '20%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxisData
            },
            yAxis: {
              type: 'value',
              name: '功率',
              min: yMin,
              max: yMax,
              splitLine: {
                show: true
              }
            },
            series: afterSeries
          };
          chartAfterInstance.setOption(afterOption, true);
        }
        
      };
      
      // 窗口大小变化处理函数
      const handleResize = () => {
        chartBeforeInstance?.resize();
        chartAfterInstance?.resize();
      };
      
      // 根据索引获取颜色
      const getColorByIndex = (index: number): string => {
        const colors = [
          '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
          '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ff9f7f',
          '#ffdb5c', '#ff9f7f', '#ff6b9d', '#c471ed', '#4facfe',
          '#00f2fe', '#43e97b', '#fa709a', '#fee140', '#30cfd0',
          '#a8edea', '#fed6e3', '#d299c2', '#fef9d7', '#89f7fe',
          '#66a6ff', '#ffecd2', '#fcb69f', '#ff8a80', '#ff80ab',
          '#ea4c89', '#ff6b95', '#f093fb', '#4facfe'
        ];
        return colors[index % colors.length];
      };
      
      // 纵向分组：每5个列为一组，整组显示浅蓝色背景
      function bandCellClassName({ column }: { column: any }) {
        const prop: string = column?.property || '';
        
        // 定义需要分组的列，按组排列
        const groupedColumns = [
          // 第1组：优化前压下率 (5列)
          's1Light', 's2Light', 's3Light', 's4Light', 's5Light',
          // 第2组：优化后压下率 (5列)
          's1New', 's2New', 's3New', 's4New', 's5New',
          // 第3组：优化后压下率占比 (5列)
          'redsFinal1New', 'redsFinal2New', 'redsFinal3New', 'redsFinal4New', 'redsFinal5New',
          // 第4组：理论最大速度 (2列)
          'maxspeedOld', 'maxspeedNew',
          // 第5组：优化前轧制力 (5列)
          'rollingforceset1', 'rollingforceset2', 'rollingforceset3', 'rollingforceset4', 'rollingforceset5',
          // 第6组：优化后轧制力 (5列)
          'rollingforceset1New', 'rollingforceset2New', 'rollingforceset3New', 'rollingforceset4New', 'rollingforceset5New',
          // 第7组：优化前电机扭矩 (5列)
          'motormomentSet1', 'motormomentSet2', 'motormomentSet3', 'motormomentSet4', 'motormomentSet5',
          // 第8组：优化后电机扭矩 (5列)
          'motormomentSet1New', 'motormomentSet2New', 'motormomentSet3New', 'motormomentSet4New', 'motormomentSet5New',
          // 第9组：优化前功率 (5列)
          'motorpower1', 'motorpower2', 'motorpower3', 'motorpower4', 'motorpower5',
          // 第10组：优化后功率 (5列)
          'motorpower1New', 'motorpower2New', 'motorpower3New', 'motorpower4New', 'motorpower5New'
        ];
        
        const columnIndex = groupedColumns.indexOf(prop);
        if (columnIndex === -1) return '';
        
        // 计算当前列属于第几组
        let groupIndex = 0;
        let currentPosition = 0;
        
        // 定义每组的大小
        const groupSizes = [5, 5, 5, 2, 5, 5, 5, 5, 5, 5];
        
        for (let i = 0; i < groupSizes.length; i++) {
          if (columnIndex < currentPosition + groupSizes[i]) {
            groupIndex = i;
            break;
          }
          currentPosition += groupSizes[i];
        }
        
        // 偶数组显示浅蓝色背景
        return groupIndex % 2 === 0 ? 'band-blue' : '';
      }

      onMounted(() => {
        fetchTableData();
        // 添加窗口大小变化监听
        window.addEventListener('resize', handleResize);
      });
      
      onUnmounted(() => {
        // 移除窗口大小变化监听
        window.removeEventListener('resize', handleResize);
        // 清理图表实例
        if (chartBeforeInstance) {
          chartBeforeInstance.dispose();
          chartBeforeInstance = null;
        }
        if (chartAfterInstance) {
          chartAfterInstance.dispose();
          chartAfterInstance = null;
        }
      });

      return {
        headerSearchForm,
        tableData,
        pagination,
        handleSearch,
        handleReset,
        handleAdd,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        dialogVisible,
        dialogTitle,
        dialogForm,
        dialogFormSubmit,
        dialogFormRules,
        dialogFormRef,
        cancel,
        handleClose,
        loading,
        handleExport,
        tableRef,
        steelGradeRangeOptions,
        widthRangeOptions,
        thicknessRangeOptions,
        bandCellClassName,
        chartBeforeRef,
        chartAfterRef,
        chartLoading,
        handleRowClick,
        currentSelectedRow,
      };
    },
  });
</script>

<style lang="less" scoped>
  @import './rollingSimulationModelCommonStyle.less';

  :deep(.el-table .cell) {
    line-height: 12px;
    padding: 4px 8px;
  }

  ::v-deep .el-table--enable-row-transition .el-table__body td {
    padding-top: 2px;
    padding-bottom: 2px;
  }

  ::v-deep .el-table__header th {
    padding: 6px 0;
  }

  ::v-deep .el-table__body tr {
    height: 32px;
  }

  ::v-deep .el-table__body td {
    padding: 2px 4px;
  }

  /* 纵向分组底色：从"优化前压下率"到"优化后功率"的一级组交替浅蓝 */
  ::v-deep(.band-blue) { 
    background-color: #f3f8ff !important; 
  }

  /* 表格容器与图表之间的留白，确保图表不被遮挡 */
  .table-container-main {
    margin-bottom: 12px;
    height: 22vh;
  }

  /* 图表容器样式 */
  .chart-container {
    margin-top: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .chart-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
    color: #303133;
  }

  .chart-item {
    width: 100%;
    height: 360px;
    min-height: 360px;
  }
</style>

